import { useStore } from '@renderer/store/useStore'
import { useCallback, useEffect } from 'react'

export default () => {
  // 下面这种写法虽然简便，但是如果state里面其他属性变化的话，这里也会重新加载，比较耗费性能
  // const { data, setData} = useStore(state => state)
  const data = useStore((state) => state.data)
  const setData = useStore((state) => state.setData)
  const setSearch = useStore((state) => state.setSearch)
  const id = useStore((state) => state.id)
  const setId = useStore((state) => state.setId)

  const handleKeyBoardEvent = useCallback(
    (e: KeyboardEvent) => {
      switch (e.code) {
        case 'ArrowUp':
          {
            if (data.length === 0) return
            // 阻止聚焦input输入框时,上箭头导致光标左移效果
            e.preventDefault()
            const index = data.findIndex((item) => item.id === id)
            setId(data[index - 1]?.id || data[data.length - 1].id)
          }
          break

        case 'ArrowDown':
          {
            if (data.length === 0) return
            // 阻止聚焦input输入框时,下箭头导致光标右移效果
            e.preventDefault()
            const index = data.findIndex((item) => item.id === id)
            setId(data[index + 1]?.id || data[0].id)
          }
          break

        case 'Enter':
          selectItem(id)
          break

        case 'Escape':
          window.api.closeWindow('search')
          break
      }
    },
    [data, id]
  )

  const selectItem = async (id: number) => {
    const content = data.find((item) => item.id === id)?.content
    if (content) await navigator.clipboard.writeText(content)
    setData([])
    setSearch('')
    window.api.closeWindow('search')
  }

  useEffect(() => {
    document.addEventListener('keydown', handleKeyBoardEvent)
    // return后面的函数是清理函数，当组件卸载或者依赖项变化时执行。
    return () => {
      document.removeEventListener('keydown', handleKeyBoardEvent)
    }
  }, [handleKeyBoardEvent])

  useEffect(() => setId(data[0]?.id || 0), [data])

  return { data, id, setId, selectItem }
}
